﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace SsTool.Utils
{
    public class TreeData<T> : INotifyPropertyChanged
    {
        private bool _isSelected;

        public T Data { get; set; }
        public List<TreeData<T>> Children { get; set; }
        public TreeData<T> Parent { get; set; }
        public bool IsSelected
        {
            get
            {
                return _isSelected;
            }
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    RaisePropertyChanged("IsSelected");

                    foreach (var item in Children)
                    {
                        item.IsSelectedFromParent = value;
                    }
                    if (this.Parent != null)
                    {
                        this.Parent.IsSelectedFromChildren = value;
                    }
                }
            }
        }

        protected bool IsSelectedFromParent
        {
            set
            {
                if (_isSelected != value)
                {
                    _isSelected = value;
                    RaisePropertyChanged("IsSelected");

                    foreach (var item in Children)
                    {
                        item.IsSelectedFromParent = _isSelected;
                    }
                }
            }
        }

        /// <summary>
        /// 只响应选中
        /// </summary>
        protected bool IsSelectedFromChildren
        {
            set
            {
                if (_isSelected != value && value == true)
                {
                    _isSelected = value;
                    RaisePropertyChanged("IsSelected");
                    if (this.Parent != null)
                    {
                        this.Parent.IsSelectedFromChildren = value;
                    }
                }
            }
        }

        public TreeData(T data)
        {
            Data = data;
            Children = new List<TreeData<T>>();
        }

        public void Add(TreeData<T> item)
        {
            Children.Add(item);
            item.Parent = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
